package com.handsome.解释器模式;

import java.util.HashMap;
import java.util.Stack;

/**
 * 计算器
 * @author niechun
 * @date 2023/3/26 15:31
 */
public class Calculator {
    //定义表达式
    private Expression expression;

    //构造器传参并解析
    public Calculator(String str) {
        //安排先后运算顺序
        Stack<Expression> stack=new Stack<>();
        //表达式拆分成数组
        char[] chars = str.toCharArray();
        Expression left=null;
        Expression right=null;
        //遍历数组
        for (int i = 0; i < chars.length; i++) {
            switch (chars[i]){
                case '+':
                    left=stack.pop();
                    right=new VarExpression(String.valueOf(chars[++i]));
                    stack.push(new AddExpression(left,right));
                    break;
                case '-':
                    left=stack.pop();
                    right=new VarExpression(String.valueOf(chars[++i]));
                    stack.push(new SubExpression(left,right));
                    break;
                default:
                    stack.push(new VarExpression(String.valueOf(chars[i])));
                    break;
            }
        }
        this.expression=stack.pop();
    }

    public int run(HashMap<String,Integer> var){
        return this.expression.interpreter(var);
    }
}
